package com.time.company.components.dynamics;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;

import com.andview.refreshview.XRefreshView;
import com.google.gson.Gson;
import com.sina.weibo.sdk.api.BaseMediaObject;
import com.sina.weibo.sdk.api.ImageObject;
import com.sina.weibo.sdk.api.MultiImageObject;
import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WebpageObject;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.utils.Utility;
import com.tencent.connect.share.QQShare;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.time.company.R;
import com.time.company.app.AddressManager;
import com.time.company.app.AppConfig;
import com.time.company.app.WXManager;
import com.time.company.base.BaseFragment;
import com.time.company.base.BasePW;
import com.time.company.base.BaseXRecAdapter;
import com.time.company.common.event.BaseEvent;
import com.time.company.components.MainActivity;
import com.time.company.components.WebDetailActivity;
import com.time.company.components.popup.SharePW;
import com.time.company.db.model.DynamicsModel;
import com.time.company.servermodel.BasicBean;
import com.time.company.servermodel.Share;
import com.time.company.servermodel.dynamics.Dynamics;
import com.time.company.servermodel.dynamics.DynamicsList;
import com.time.company.utils.NetWorkUtils;
import com.time.company.utils.ShareUtils;
import com.time.company.utils.ToastUtils;
import com.time.company.viewmodel.DynamicsViewModel;
import com.time.company.views.CustomHeaderView;
import com.time.company.views.CustomerFooter;
import com.time.company.webserver.helper.WebServerManager;
import com.time.company.webserver.request.BasicRequest;
import com.time.company.webserver.request.requestsParamters.DynamicsParameters;
import com.yanzhenjie.nohttp.Logger;
import com.yanzhenjie.nohttp.rest.Request;
import com.yanzhenjie.nohttp.rest.Response;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;
import com.zhy.base.fileprovider.FileProvider7;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;

/**
 * 动态
 * Created by Bing on 2017/10/25.
 * E-mail is tx16bing@163.com
 */

public class DynamicsFragment extends BaseFragment implements
        BaseXRecAdapter.OnItemClickListener {

    public static final int REQUEST_STORAGE_PERMISSION = 101;

    private LinearLayout llParent;
    private LinearLayout llEmpty;
    private XRefreshView xRefreshView;
    private RecyclerView rvDynamics;

    private List<DynamicsViewModel> mDynamics;
    private Share share;
    private DynamicsAdapter mAdapter;

    private Request request;
    private static final int REFRESH_DYNAMICS_WHAT = 201;
    private static final int LOAD_DYNAMICS_WHAT = 202;
    private static final int LIKE_DYNAMICS_WHAT = 203;
    private static final int SHARE_TOPIC_WHAT = 204;

    private WindowManager.LayoutParams attributes;
    private SharePW sharePW;

    // qq
    private Tencent mTencent;

    private String curChannel;
    private String localPicUrl;

    @Override
    public void initContentView(View contentView) {
        EventBus.getDefault().register(this);
        assignViews();

        if (mTencent == null) {
            mTencent = Tencent.createInstance(mContext.getString(R.string.qq_app_id), mContext);
        }
    }

    @Override
    public void initData() {
        super.initData();
        this.mDynamics = new ArrayList<>();
        List<DynamicsViewModel> dynamicsViewModels = mVMcreator.getDynamicsViewModels();
        if (null != dynamicsViewModels) {
            this.mDynamics = dynamicsViewModels;
            setAdapter();
        }
    }

    @Override
    public int bindLayoutId() {
        return R.layout.fragment_dynamics;
    }

    private void assignViews() {
        llParent = findView(R.id.ll_dynamics_parent);
        llEmpty = findView(R.id.ll_no_result);
        xRefreshView = findView(R.id.dynamics_refresh);
        rvDynamics = findView(R.id.rv_dynamics);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        rvDynamics.setItemAnimator(new DefaultItemAnimator());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvDynamics.setLayoutManager(linearLayoutManager);
        rvDynamics.setHasFixedSize(true);

        xRefreshView.setPinnedTime(1000);
        xRefreshView.setPullLoadEnable(true);
        xRefreshView.setMoveForHorizontal(true);
        xRefreshView.setAutoLoadMore(false);
        xRefreshView.setCustomHeaderView(new CustomHeaderView(mContext, 1000));
        xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {

            @Override
            public void onRefresh(boolean isPull) {
                setRequest(getString(R.string.zero), REFRESH_DYNAMICS_WHAT);
            }

            @Override
            public void onLoadMore(boolean isSilence) {
                if (mDynamics != null && !mDynamics.isEmpty()) {
                    String loadId = mDynamics.get(mDynamics.size() - 1).getDynamicsId();
                    Logger.i("Load id " + loadId);
                    setRequest(loadId + "", LOAD_DYNAMICS_WHAT);
                }
            }
        });
        xRefreshView.setHideFooterWhenComplete(true);
        xRefreshView.setAutoRefresh(true);
    }

    private void bindEmpty(){
        if (mDynamics == null) return;
        if (mDynamics.isEmpty()){
            llEmpty.setVisibility(View.VISIBLE);
            xRefreshView.setVisibility(View.GONE);
        }else {
            llEmpty.setVisibility(View.GONE);
            xRefreshView.setVisibility(View.VISIBLE);
        }

    }

    private void setAdapter() {
        if (mAdapter == null) {
            mAdapter = new DynamicsAdapter(mContext, mDynamics, 1);
            mAdapter.setOnItemClickListener(this);
            rvDynamics.setAdapter(mAdapter);
        } else {
            mAdapter.updateData(mDynamics);
        }

        if (mDynamics.size() >= 10) {
            xRefreshView.setPullLoadEnable(true);
            CustomerFooter customerFooter = new CustomerFooter(mContext);
            customerFooter.setRecyclerView(rvDynamics);
            customerFooter.callWhenNotAutoLoadMore(xRefreshView);
            mAdapter.setCustomLoadMoreView(customerFooter);
        } else {
            xRefreshView.setPullLoadEnable(false);
        }

    }

    @Override
    public void onItemClick(View view, int position, Object o, int type) {
        // Adapter item click
        DynamicsViewModel dynamics = null;
        if (o instanceof DynamicsViewModel) {
            dynamics = (DynamicsViewModel) o;
        }

        switch (view.getId()) {

            case R.id.ll_item_dynamics_list_parent:
                // 动态详情
                String url = new StringBuilder().append(AddressManager.getInstance().getWebAddress())
                        .append("/dynamics-detail/")
                        .append(application.isLogin() ? application.getAccount() : "-1")
                        .append("/android/")
                        .append(dynamics.getDynamicsId())
                        .toString();
                WebDetailActivity.start(mContext,
                        application.getString(R.string.dynamics_details),
                        url);
                break;

            case R.id.iv_dynamics_share:
                // 分享界面
                if (share == null){
                    share = new Share();
                }
                share.setShareId(dynamics.getDynamicsId());
                share.setAppName(getString(R.string.app_name));

                // 需要调用AndPermission来开启读写系统文件夹权限提示
                AndPermission.with(this)
                        .requestCode(REQUEST_STORAGE_PERMISSION)
                        .permission(Manifest.permission.READ_EXTERNAL_STORAGE,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .callback(listener)
                        // rationale作用是：用户拒绝一次权限，再次申请时先征求用户同意，再打开授权对话框；
                        // 这样避免用户勾选不再提示，导致以后无法申请权限。
                        // 你也可以不设置。
                        .rationale(new RationaleListener() {
                            @Override
                            public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                                // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                                AndPermission.rationaleDialog(mContext, rationale)
                                        .show();
                            }
                        })
                        .start();

                break;

            case R.id.iv_dynamics_is_like:
                // 点赞
                if (TextUtils.isEmpty(dynamics.getLikeNum())) {
                    dynamics.setLikeNum("1");
                } else {
                    String num = dynamics.getLikeNum();
                    int newNum = Integer.parseInt(num) + 1;
                    dynamics.setLikeNum(newNum + "");
                }
                mAdapter.notifyDataSetChanged();
                likeRequest(dynamics.getDynamicsId());
                break;

            case R.id.riv_dynamics_head:
                // 点击头像进入企业荣誉
                String honorUrl = new StringBuilder().append(AddressManager.getInstance().getWebAddress())
                        .append("/honor/")
                        .append(application.isLogin() ? application.getAccount() : "-1")
                        .append("/android/")
                        .append(dynamics.getUserId())
                        .toString();
                Logger.i("Honor url " + honorUrl);
                WebDetailActivity.start(mContext, getString(R.string.task_honor), honorUrl);
                break;

            default:
                break;

        }
    }

    // 权限回调监听
    private PermissionListener listener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
            if (requestCode == REQUEST_STORAGE_PERMISSION) {
                // 表示读写的权限申请通过
                AppConfig.getInstance().initDir();

                if (sharePW == null || !sharePW.isShowing()) {
                    launchShare();
                } else {
                    return;
                }

            }
        }

        @Override
        public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
            if (requestCode == REQUEST_STORAGE_PERMISSION) {
                // 即使是用户选择了不在询问还是会toast该提示语
                ToastUtils.showShort(getString(R.string.external_permission_apply));
            }

            // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
            if (AndPermission.hasAlwaysDeniedPermission(mContext, deniedPermissions)) {
                // 第一种：用默认的提示语。
                AndPermission.defaultSettingDialog(mContext, 404).show();

            }
        }
    };

    private void launchShare() {
        final Window window = mContext.getWindow();
        attributes = window.getAttributes();
        attributes.alpha = 0.5f;
        window.setAttributes(attributes);
        sharePW = new SharePW(mContext, llParent);
        sharePW.setOnItemClickListener(new BasePW.OnItemClickListener<String>() {
            @Override
            public void onItemClick(final int type, String result) {
                if (type == resources.getInteger(R.integer.share_type_wx)) {
                    curChannel = application.getString(R.string.share_channel_friend);
                } else if (type == resources.getInteger(R.integer.share_type_wx_publish)) {
                    curChannel = application.getString(R.string.share_channel_moment);
                } else if (type == resources.getInteger(R.integer.share_type_qq)) {
                    curChannel = application.getString(R.string.share_channel_qq);
                }else if ( type == resources.getInteger(R.integer.share_type_qq)) {
                    curChannel = application.getString(R.string.share_channel_qq_zone);
                } else if (type == resources.getInteger(R.integer.share_type_wb)) {
                    curChannel = application.getString(R.string.share_channel_wei_bo);
                } else {
                    return;
                }

                shareRequest();
            }
        });
        sharePW.showAtLocation(llParent, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        sharePW.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                attributes.alpha = 1.0f;
                window.setAttributes(attributes);
            }
        });
    }

    public void shareRequest() {
        if (NetWorkUtils.isNetAvailable(application)) {
            request = new BasicRequest(AddressManager.getInstance().getAddress());
            DynamicsParameters parameters = new DynamicsParameters();
            parameters.setCommand(getString(R.string.command_shareTopic));
            parameters.setUserId(application.getAccount());
            parameters.setDynamicsId(share.getShareId());
            parameters.setThirdParty(curChannel);
            request.add(getString(R.string.command), parameters.getCommand());
            request.add(getString(R.string.platform), parameters.getPlatform());
            request.add(getString(R.string.data), new Gson().toJson(parameters));
            request.setCancelSign(toString());
            WebServerManager.getInstance().add(mContext, request, this,
                    SHARE_TOPIC_WHAT, true, true, true);
        } else {
            ToastUtils.showShort(getString(R.string.network_error));
        }
    }

    public void shareOnQQ(final int type, Share share) {
        final Bundle params = new Bundle();
        params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, share.getAddress());
        params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL, share.getPicUrl());
        params.putString(QQShare.SHARE_TO_QQ_TITLE, share.getTitle());
        params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "您好时间");
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_IMAGE);

        mContext.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (type == resources.getInteger(R.integer.share_type_qq_zone)) {
                    if (null != mTencent) {
                        params.putInt(QQShare.SHARE_TO_QQ_EXT_INT, QQShare.SHARE_TO_QQ_FLAG_QZONE_AUTO_OPEN);
                        mTencent.shareToQQ(mContext, params, qqShareListener);
                    }
                } else {
                    if (null != mTencent) {
                        mTencent.shareToQQ(mContext, params, qqShareListener);
                    }
                }

            }
        });
    }

    private void shareMoment(Share share, boolean isTimelineCb, String localPicUrl) {
        WXManager.instance().sendWebPageToWX(
                isTimelineCb,
                share.getAddress(),
                TextUtils.isEmpty(share.getTitle()) ? " " : share.getTitle(),
                share.getDescribe(),
                localPicUrl);
    }

    /**
     * 第三方应用发送请求消息到微博，唤起微博分享界面。
     */
    private void shareWeibo(Share share, String localPicUrl) {
        WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
        weiboMessage.textObject = getTextObj(share);
        weiboMessage.imageObject = getImageObj();
        weiboMessage.mediaObject = getWebpageObj(share);
        weiboMessage.multiImageObject = getMultiImageObject(share, localPicUrl);
        ((MainActivity) mContext).shareHandler.shareMessage(weiboMessage, false);

    }

    /**
     * 创建文本消息对象。
     *
     * @return 文本消息对象。
     */
    private TextObject getTextObj(Share share) {
        TextObject textObject = new TextObject();
        textObject.text = share.getTitle();
        return textObject;
    }

    private ImageObject getImageObj() {
        ImageObject imageObject = new ImageObject();
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.iv_share_wb);
        imageObject.setImageObject(bitmap);
        return imageObject;
    }

    private BaseMediaObject getWebpageObj(Share share) {
        WebpageObject mediaObject = new WebpageObject();
        mediaObject.identify = Utility.generateGUID();
        mediaObject.title = share.getTitle();
        mediaObject.description = getString(R.string.app_name);
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.iv_logo);
        // 设置 Bitmap 类型的图片到视频对象里         设置缩略图。 注意：最终压缩过的缩略图大小不得超过 32kb。
        mediaObject.setThumbImage(bitmap);
        mediaObject.actionUrl = share.getAddress();
        mediaObject.defaultText = "Webpage 默认文案";
        return mediaObject;
    }

    private MultiImageObject getMultiImageObject(Share share, String localPicUrl) {
        MultiImageObject multiImageObject = new MultiImageObject();
        //pathList设置的是本地本件的路径,并且是当前应用可以访问的路径，现在不支持网络路径（多图分享依靠微博最新版本的支持，所以当分享到低版本的微博应用时，多图分享失效
        // 可以通过WbSdk.hasSupportMultiImage 方法判断是否支持多图分享,h5分享微博暂时不支持多图）多图分享接入程序必须有文件读写权限，否则会造成分享失败
        ArrayList<Uri> pathList = new ArrayList<>();
        pathList.add(FileProvider7.getUriForFile(mContext, new File(localPicUrl)));
        multiImageObject.setImageList(pathList);
        return multiImageObject;
    }

    private void likeRequest(String id) {
        if (NetWorkUtils.isNetAvailable(application)) {
            request = new BasicRequest(AddressManager.getInstance().getAddress());
            DynamicsParameters parameters = new DynamicsParameters();
            parameters.setCommand(application.getString(R.string.command_likeTopic));
            parameters.setUserId(application.getAccount());
            parameters.setDynamicsId(id);
            request.add(application.getString(R.string.command), parameters.getCommand());
            request.add(application.getString(R.string.platform), parameters.getPlatform());
            request.add(application.getString(R.string.data), new Gson().toJson(parameters));
            request.setCancelSign(toString());

            WebServerManager.getInstance().add(mContext, request, this,
                    LIKE_DYNAMICS_WHAT, false, false, true);
        } else {
            ToastUtils.showShort(application.getString(R.string.network_error));
        }
    }


    private void setRequest(String id, int what) {
        if (NetWorkUtils.isNetAvailable(application)) {
            request = new BasicRequest(AddressManager.getInstance().getAddress());
            DynamicsParameters parameters = new DynamicsParameters();
            parameters.setCommand(application.getString(R.string.command_getTopicList));
            parameters.setUserId(application.getAccount());
            parameters.setDynamicsId(id);
            request.add(application.getString(R.string.command), parameters.getCommand());
            request.add(application.getString(R.string.platform), parameters.getPlatform());
            request.add(application.getString(R.string.data), new Gson().toJson(parameters));
            request.setCancelSign(toString());
            WebServerManager.getInstance().add(mContext, request, this,
                    what, false, false, true);
        } else {
            ToastUtils.showShort(application.getString(R.string.network_error));
        }
    }

    @Override
    public void onSucceed(int what, Response<BasicBean> response) {
        BasicBean basicBean = response.get();
        if (basicBean == null) {
            endRequest();
            return;
        }

        if (basicBean.isSuccess()) {
            if (what == REFRESH_DYNAMICS_WHAT || what == LOAD_DYNAMICS_WHAT) {
                DynamicsList dynamicsList = basicBean.parseData(DynamicsList.class);
                if (dynamicsList == null) {
                    endRequest();
                    return;
                }

                List<Dynamics> dynamicses = dynamicsList.getDynamicses();
                if (dynamicses == null) {
                    endRequest();
                    return;
                }
                if (what == REFRESH_DYNAMICS_WHAT) {
                    endRefreshing();
                    List<DynamicsViewModel> dynamicsViewModels =
                            mVMcreator.setDynamicsViewModels((ArrayList<Dynamics>) dynamicses);
                    if (null != dynamicsViewModels) {
                        this.mDynamics = dynamicsViewModels;
                        bindEmpty();
                        setAdapter();
                    }

                } else {
                    if (dynamicses.isEmpty()) {
                        endRequest();
                        return;
                    }
                    endLoading();
                    for (Dynamics topic : dynamicses) {
                        DynamicsModel model = new DynamicsModel(topic);
                        this.mDynamics.add(new DynamicsViewModel(application, model));
                    }
                    bindEmpty();
                    setAdapter();
                }

            } else if (what == LIKE_DYNAMICS_WHAT) {
                ToastUtils.showShort("点赞成功");
            } else if (what == SHARE_TOPIC_WHAT){
                Share tempShare = basicBean.parseData(Share.class);
                if (tempShare == null) return;
                share.setTitle(tempShare.getTitle());
                share.setAddress(tempShare.getAddress());
                share.setPicUrl(tempShare.getPicUrl());
                share.setDescribe(tempShare.getDescribe());
                ShareUtils.getInstance().getSharePicPath(share.getPicUrl(), "share.jpg", new ShareUtils.ShareCallback() {
                    @Override
                    public void onSucceed(String path) {
                        localPicUrl = path;
                        if (TextUtils.isEmpty(localPicUrl)){
                            localPicUrl = ShareUtils.getInstance().getSharePicPath("share.jpg");
                        }

                        if (TextUtils.equals(curChannel, getString(R.string.share_channel_friend))){
                            //　分享给微信朋友
                            shareMoment(share, false, localPicUrl);
                        } else if (TextUtils.equals(curChannel, getString(R.string.share_channel_moment))) {
                            //　分享给微信朋友圈
                            shareMoment(share, true, localPicUrl);
                        } else if (TextUtils.equals(curChannel, getString(R.string.share_channel_qq_zone))) {
                            // 分享给QQ空间
//                          shareOnQQ(share, localPicUrl);
                        } else if (TextUtils.equals(curChannel, getString(R.string.share_channel_wei_bo))) {
                            // 分享给微博
                            shareWeibo(share, localPicUrl);
                        } else {
                            return;
                        }
                    }
                });
            }
        } else {
            ToastUtils.showShort(basicBean.getMsg());
            endRequest();
        }
    }

    private void endRequest() {
        endRefreshing();
        endLoading();
    }

    private void endRefreshing() {
        xRefreshView.stopRefresh();
    }

    private void endLoading() {
        xRefreshView.stopLoadMore();
    }

    IUiListener qqShareListener = new IUiListener() {
        @Override
        public void onCancel() {
            ToastUtils.showShort("Cancel");
        }

        @Override
        public void onComplete(Object response) {
            ToastUtils.showShort("Complete");
        }

        @Override
        public void onError(UiError e) {
            ToastUtils.showShort("Error : " + e.errorMessage);
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // qq
        Tencent.onActivityResultData(requestCode, resultCode, data, qqShareListener);
    }

    @Subscribe
    public void onEventMainThread(BaseEvent event){
        if (TextUtils.isEmpty(event.getBaseType())) {
            return;
        }
        if (TextUtils.equals(event.getBaseType(), getString(R.string.refresh_dynamics_fragment_data))) {
            setRequest(getString(R.string.zero), REFRESH_DYNAMICS_WHAT);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        EventBus.getDefault().unregister(this);

        if (null != sharePW) {
            sharePW.dismiss();
            sharePW = null;
        }
    }
}
